package cn.zysheep.controller;

import cn.zysheep.utils.ConstantPropertiesUtils;
import cn.zysheep.utils.HttpClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/api/wx")
public class WxController {

    /**
     * 生成订单号
     * @return
     */
    public static String getOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }

    /**
     * 元转换成分
     * @param amount
     * @return
     */
    public static String getMoney(String amount) {
        if(amount==null){
            return "";
        }
        // 金额转化为分为单位
        // 处理包含, ￥ 或者$的金额
        String currency =  amount.replaceAll("\\$|\\￥|\\,", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if(index == -1){
            amLong = Long.valueOf(currency+"00");
        }else if(length - index >= 3){
            amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));
        }else if(length - index == 2){
            amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
        }else{
            amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
        }
        return amLong.toString();
    }


    @GetMapping("/pay")
    public String createNative(Model model) {
        try {
            String orderNo = getOrderNo();
            String price = "1";
            //3设置参数，
            //把参数转换xml格式，使用商户key进行加密
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            paramMap.put("body", "微信支付测试");//主体信息
            paramMap.put("out_trade_no",orderNo);
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", price); //为了测试，统一写成这个值
            paramMap.put("spbill_create_ip", "127.0.0.1");//项目的域名
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//回调地址
            paramMap.put("trade_type", "NATIVE");//生成二维码的类型
            //4 调用微信生成二维码接口,httpclient调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置map参数
            //设置xml格式的参数
            //把xml格式的数据加密
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //5.得到发送请求返回结果
            //返回内容，是使用xml格式返回
            String xml = client.getContent();
            //转换map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("resultMap:"+resultMap);
            //6 封装返回结果集
            Map map = new HashMap<>();
            map.put("orderId", orderNo);
            map.put("totalFee", price);
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url")); //二维码地址

            ObjectMapper objectMapper = new ObjectMapper();
            String sMap = objectMapper.writeValueAsString(map);

            model.addAttribute("map",sMap);
            return "pay";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @GetMapping("queryOrder/{orderNo}")
    @ResponseBody
    public String queryPayStatus(@PathVariable String orderNo) throws Exception{
        //1 封装提交参数
        Map paramMap = new HashMap();
        //公众账号ID
        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        //商户号
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        //商户订单号
        paramMap.put("out_trade_no", orderNo);
        //随机字符串
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

        //2 设置请求内容
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
        client.setHttps(true);
        client.post();

        //3 得到微信接口返回数据
        String xml = client.getContent();
        Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
        System.out.println("支付状态resultMap:"+resultMap);
        //5 把接口数据返回
        //4.判断是否支付成功
        if("SUCCESS".equals(resultMap.get("trade_state"))) {//支付成功
            //更新订单状态
            /*
                  改变数据库中的数据等操作
             */
            return "支付成功";
        }
        return "支付中";

    }


    @GetMapping("success")
    public String success(){
        return "success";
    }


}
